<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\ModelFilters\AdminFilter;
use App\Models\BlogUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use mysql_xdevapi\DatabaseObject;

class AdminController extends Controller
{
    /**
     * 所有用户列表
     * @param int $id 用户id
     * @param string $username 用户名
     * @param string $sex 性别
     * @param string $created_at 创建时间
     * @param string $updated_at 更新时间
     */
    public function index(BlogUser $user)
    {
//        $model = BlogUser::filter($request->all());
//        return paginate($model);

        $userinfo = BlogUser::all();
        return success_json(compact('userinfo'));

    }

    /**
     *
     */
    public function create()
    {

    }

    /**
     *  添加用户
     * @param  string  $username 用户名
     * @param  string  $password 密码
     */
    public function store(Request $request)
    {
        $rules = [
          'username' => 'required',
          'password' => 'required|min:6'
        ];

        $this->validate($request,$rules);

        $username = $request->input('username');
        $password = $request->input('password');

        //判断账号是否存在
        $user = BlogUser::where('username',$username)->first();
        if ($user) return error_json('用户名已存在');

        //保存密码
        BlogUser::create([
            'username' => $username,
            'password' => $password,
        ]);

        return success_json('添加成功');
    }

    /**
     * 查找单个用户信息
     */
    public function show(BlogUser $user)
    {
        $user->load('profile','role');
        return success_json($user);
    }


    /**
     * 修改密码
     * @param string password 密码
     * @param string sex 性别
     * @param string images 用户头像
     */
    public function update(BlogUser $user,Request $request)
    {
        $rules = [
          'password' => 'required|min:6',
        ];
        $this->validate($request,$rules);

        $password = $request->input('password');

        $user->update([
            'password' => $password,
        ]);

        return success_json('修改成功');
    }

    /**
     * 删除用户
     */
    public function destroy(BlogUser $user)
    {
        $user->delete();

        return success_json('删除成功');
    }
}
